#include <semaphore.h>
#include <stdio.h>
#include <pthread.h>

#define N 10

sem_t space, prod;

int Buffer[N];
int in=0, out =0; 

int amount = 20;

void * producer(void *p){
    while(amount--){
        sem_wait(&space);
        printf("Put a product into Buffer[%d]!\n", in);
        in = (in +1)%N; 
        sem_post(&prod);
    } 
    return NULL;
}

void * consumer(void *p){
    while(1){
        sem_wait(&prod);
        printf ("Get a product from Buffer[%d]!\n", out);
        out = (out +1)%N; 
        sem_post(&space);
     }  
     return NULL;
}


int main(void)
{
    sem_init(&space, 0, N); 
    sem_init(&prod, 0, 0);
    pthread_t tid[2];
    pthread_create(&tid[0], NULL, producer, NULL);
    pthread_create(&tid[1], NULL, consumer, NULL);
    sem_destroy(&space); 
    pthread_join(tid[0], NULL);
}